package n60_unsafe;

import sun.misc.Unsafe;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author fu
 * @date 2022-02-19 18:37
 * 概要：
 * ---------------------------------------------------------------
 * |                                                              |
 * |                  |
 * |                                                             |
 * |=============================================================
 */
public class T3_MyAtomicInteger_利用Unsafe写一个 {

    public static void main(String[] args) {
        Account.demo(new AccountCas(10000));
    }


}
// 利用Unsafe写一个 线程安全的 整型原子类
class MyAtomicInteger{

    private volatile int data;
    static final Unsafe unsafe;
    static final long DATA_OFFSET;

    static {
        unsafe = T1_UnsafeAccessor_非常底层的操作内存和线程方法.getUnsafe();
        try {
            // data 属性在 DataContainer 对象中的偏移量，用于 Unsafe 直接访问该属性
            DATA_OFFSET = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("data"));
        } catch (NoSuchFieldException e) {
            throw new Error(e);
        }
    }

    public MyAtomicInteger(int data) {
        this.data = data;
    }
    // 模拟 AtomicInteger 方法
    public void getAndAdd(int amount) {
        int oldValue;
        while(true) {
            // 获取共享变量旧值，可以在这一行加入断点，修改 data 调试来加深理解
            oldValue = data;
            // cas 尝试修改 data 为 旧值 + amount，如果期间旧值被别的线程改了，返回 false
            if (unsafe.compareAndSwapInt(this, DATA_OFFSET, oldValue, oldValue + amount)) {
                break;
            }
        }
    }

    public int get() {
        return data;
    }

}


class AccountCas implements Account {

//HEAD >>>>>>>>>>>>>>>>>>>>>>>>>>>>
    // jdk提供的 原子整数
/*    private AtomicInteger balance;

    public AccountCas(int balance) {
        this.balance = new AtomicInteger(balance);
    }*/
//=================================
    private MyAtomicInteger balance;

    public AccountCas(int balance) {
        this.balance = new MyAtomicInteger(balance);
    }
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public Integer getBalance() {
        return balance.get();
    }


    @Override
    public void withdraw(Integer amount) {

        balance.getAndAdd(-1 * amount);
    }
}


interface Account {
    // 获取余额
    Integer getBalance();
    // 取款
    void withdraw(Integer amount);
    /**
     * 方法内会启动 1000 个线程，每个线程做 -10 元 的操作
     * 如果初始余额为 10000 那么正确的结果应当是 0
     */
    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        long start = System.nanoTime();

        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }

        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        long end = System.nanoTime();
        System.out.println("最终余额 = " + account.getBalance()
                + " 。 执行时间cost= " + (end-start)/1000_000 + " ms");
    }
}